<%@ page session="true"%>
<%@ page import="java.util.Map,java.util.Iterator,org.email4java.discovery.Identifier,org.email4java.discovery.DiscoveryInformation,org.email4java.message.ax.FetchRequest,org.email4java.message.ax.FetchResponse,org.email4java.message.ax.AxMessage,org.email4java.message.*,org.email4java.emailException,java.util.List,java.io.IOException,javax.servlet.http.HttpSession,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,org.email4java.consumer.ConsumerManager,org.email4java.consumer.InMemoryConsumerAssociationStore,org.email4java.consumer.InMemoryNonceVerifier"%>
<%@ page import="org.email4java.emailException,org.email4java.util.*"%>
<%@ page import="org.springframework.context.ApplicationContext" %>
<%@ page import="org.springframework.context.support.ClassPathXmlApplicationContext"%>
<%@ page import="org.biojava.services.das.registry.ConfigBean" %>
<%@ page import="org.email4java.consumer.*" %>
<%@ page import="net.sf.ehcache.*" %>
<%@ page import="dasregistry.RegistryEhCache" %>
<%@ page import="org.email4java.message.sreg.*" %>
<%@ include file="sangerheader.jsp"%>
<%

ApplicationContext context = new ClassPathXmlApplicationContext("config_dasregistry.xml");
ConfigBean conf = (ConfigBean) context.getBean("configBean");

//determine a return_to URL where your application will receive
// the authentication responses from the email provider
// YOU SHOULD CHANGE THIS TO GO TO THE
String returnToUrl = conf.getemailReturnURL();
//
System.out.print("got returnToURL: " + returnToUrl);
//System.out.println("consumer_returnurl:" + returnToUrl);
System.out.println("AA - " + request.getServerName() + " " + request.getServerPort() );
//
//session.setAttribute("email",request.getParameter("email"));

%>

<% 
	email   = request.getParameter("email");
System.out.println("request open id in consumer_redirect="+email);
	String remember = request.getParameter("remember"); 
	
	if (( remember != null ) && (remember.equals("1"))){
		// set cookie with email name
		
	       Cookie mycookie = new Cookie("claimedemailName",email);
		   int maxAge = 60*60*24 *180 ; // 180 days
		   try {
			   	maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
		   } catch (Exception e) {
				//e.printStackTrace();
		   }
		   mycookie.setMaxAge(maxAge);	
	       response.addCookie(mycookie);
	 
	} else {
		   Cookie mycookie = new Cookie("claimedemailName","");
	       response.addCookie(mycookie);	       
	 
	}
%>




<%@ include file="consumer_init.jsp" %>  

<%
	// README:
	// Set the returnToUrl string to the appropriate value for this JSP
	// Since you may be deployed behind apache, etc, the jsp has no real idea what the
	// absolute URI is to get back here.



	try {
		
	if(manager==null)manager=(ConsumerManager)session.getAttribute("consumermanager");
	if(manager==null)manager=new ConsumerManager();
	session.setAttribute("consumermanager",manager);
		// perform discovery on the user-supplied identifier
		System.out.println("email in consumer redirect="+email);
		List discoveries = manager.discover(email);

		// attempt to associate with an email provider
		// and retrieve one service endpoint for authentication
		DiscoveryInformation discovered = manager.associate(discoveries);

		// store the discovery information in the user's session
		session.setAttribute("email-disco", discovered);
		System.out.println("discovered in consumer_redirect: " + discovered);
		// obtain a AuthRequest message to be sent to the email provider
		
		SRegRequest sregReq = SRegRequest.createFetchRequest();

		//sregReq.addAttribute("fullname", true);
		//sregReq.addAttribute("nickname", true);
		sregReq.addAttribute("email", true);

		AuthRequest authReq = manager.authenticate(discovered,returnToUrl);
		authReq.addExtension(sregReq);
      
		
		// Attribute Exchange example: fetching the 'email' attribute
		///*
		//FetchRequest fetch = FetchRequest.createFetchRequest();
		//fetch.addAttribute("email",
		// attribute alias
		//       "http://schema.email.net/contact/email",   // type URI
		//       true);                                      // required

		// attach the extension to the authentication request
		//authReq.addExtension(fetch);
		//*/
		if (!discovered.isVersion2()) {
	// Option 1: GET HTTP-redirect to the email Provider endpoint
	// The only method supported in email 1.x
	// redirect-URL usually limited ~2048 bytes
		String authUrl = authReq.getDestinationUrl(true);
		System.out.println("sending error to authUrl="+authUrl);
		response.sendRedirect(authUrl);
	
	// email hack from email4java mailing list:
		//System.out.println("adding email yo email request");
			//String authUrl = authReq.getDestinationUrl(true);
			//authUrl = authUrl + "&email.sreg.required=email";
            //authUrl = authUrl + "&email.sreg.required=email%2Cnickname";
            //response.sendRedirect(authUrl);
            return ; 
	
	
		} else {
	// Option 2: HTML FORM Redirection
	// Allows payloads > 2048 bytes

	// <FORM action="email Provider's service endpoint">
	// see samples/formredirection.jsp for a JSP example
	//authReq.getOPEndpoint();

	// build a HTML FORM with the message parameters
	//authReq.getParameterMap();
%>

<%@page import="dasregistry.RegistryEhCache;"%>
<html>
<head>
<title>email HTML FORM Redirection</title>
</head>
<body onload="document.forms['email-form-redirection'].submit();">
<body>
<p>You will be automatically redicted to <a
	href="<%= authReq.getOPEndpoint() %>"><%= authReq.getOPEndpoint() %></a>, in order to
authenticate your login.</p>
<p>If the redirect fails please press the Continue button.</p>


<form name="email-form-redirection"
	action="<%= authReq.getOPEndpoint() %>" method="post"
	accept-charset="utf-8">
<%
	Map pm = authReq.getParameterMap();
	Iterator keyit = pm.keySet().iterator();

	Object key;
	Object value;

	while (keyit.hasNext()) {
		key = keyit.next();
		value = pm.get(key);
		
		
		System.out.println("key in open-id-form-redirct= "+key + " " + value);
%> <input type="hidden" name="<%= key%>" value="<%= value%>" /> 
<%
 }
	
 %>
 <input type="hidden" name="email.sreg.required" value="email"/>
<button type="submit">Continue...</button>
</form>
</body>
</html>
<%
	}
	} catch (emailException e) {
		System.out.println("caught error in consumer_redirect");
		e.printStackTrace();
		// present error to the user
		//response.sendError(500);
		session.setAttribute("message", e.getMessage());
		System.out.println("setting message " + e.getMessage());
		session.removeAttribute("email");
		String newUrl = "login.jsp";
		response.sendRedirect(newUrl);

	}
%>
